package com.tq68.weixin.utils;

import com.jfinal.kit.HashKit;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.tq68.weixin.vo.JssdkVO;

public class JssdkParamUtil {

	public JssdkVO getWebParam(String requestUrl){
		JssdkVO jssdk = new JssdkVO();
		ApiConfigKit.setThreadLocalApiConfig(getApiConfig()); //必须
        JssdkTicket jssdkTicket = JssdkTicketUtil.getJssdkTicket();
        if (!jssdkTicket.getErrmsg().equals("ok")){
        	jssdk.setErrorMsg("加载JS-SDK出错。");
        }else {
            String timestamp = (java.lang.System.currentTimeMillis()+"").substring(0,10);
            String noncestr = HashKit.generateSalt(16);//随机字符串
            String tempStr = "jsapi_ticket=" + jssdkTicket.getTicket() + "&noncestr="+noncestr+"&timestamp=" + timestamp + "&url=" + requestUrl+"";
            tempStr = HashKit.sha1(tempStr);
            jssdk.setNonceStr(noncestr);
            jssdk.setTimestamp(timestamp);
            jssdk.setSignature(tempStr);
        }
        return jssdk;
	}

	private ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();
				
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appId"));
		ac.setAppSecret(PropKit.get("appSecret"));
		
		/**
		 *  是否对消息进行加密，对应于微信平台的消息加解密方式：
		 *  1：true进行加密且必须配置 encodingAesKey
		 *  2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
		return ac;
	}
}
